package com.mark.web.data.service.impl;

import com.mark.common.Constant;
import com.mark.common.ServerResponse;
import com.mark.web.data.mapper.SellerMapper;
import com.mark.web.data.enums.UserStateEnum;
import com.mark.web.data.exception.SellerException;
import com.mark.web.data.entity.po.Seller;
import com.mark.web.data.service.ISellerService;
import com.mark.web.data.util.JsonUtil;
import com.mark.web.sys.entity.po.User;
import com.mark.web.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 店家信息业务逻辑实现
 * @Author: Mark
 * @CreateDate: 2018/8/14.
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Service("iSellerService")
public class SellerServiceImpl implements ISellerService {
    @Autowired
    private SellerMapper sellerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ServerResponse<String> register(Seller seller, String loginToken) {
        try {
            int resultCount = sellerMapper.insert(seller);
            if (resultCount > 0) {
                User user = new User();
                user.setId(seller.getUserId());
                // TODO: 2019/1/20
                //user.setRole(UserStateEnum.SELLER_CUSTOMER.getRole());//设置注册身份为普通用户
                resultCount = userMapper.updateByPrimaryKeySelective(user);
                if (resultCount > 0) {
                    User currentUser = userMapper.selectByPrimaryKey(seller.getUserId());
                    //因为升级为店家User的角色，seller的相关操作需要根据role进行判断。所以需要重新更新Redis中user的信息
                    //RedisShardedPoolUtil.setEx(loginToken, JsonUtil.obj2String(currentUser), Constant.RedisCacheExtime.REDIS_SESSION_EXTIME);
                    redisTemplate.opsForValue().set(loginToken,JsonUtil.obj2String(currentUser),
                            Constant.RedisCacheExtime.REDIS_SESSION_EXTIME, TimeUnit.SECONDS);
                    return ServerResponse.createBySuccessMessage("注册成功！");
                }
            }
            return ServerResponse.createByErrorMessage("注册失败！");
        } catch (Exception e){
            throw new SellerException("register",e.getClass()+e.getMessage());
        }
    }
}
